package site.qjdb.config.listener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import site.qjdb.constant.Info;
import site.qjdb.pojo.Goods;
import site.qjdb.pojo.Want;
import site.qjdb.pojo.pagination.PageBean;
import site.qjdb.pojo.temp.ActiveUser;
import site.qjdb.pojo.temp.IndexGoods;
import site.qjdb.service.GoodsService;
import site.qjdb.service.WantService;

@Slf4j
public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> {
	private WantService wantService;
	private GoodsService goodsService;

	/**
	 * Spring初始化，刷新会执行此方法
	 * 
	 * */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 防止执行多次
		if(event.getApplicationContext().getParent() == null) {
			ApplicationContext context = event.getApplicationContext();
			wantService = context.getBean(WantService.class);
			goodsService = context.getBean(GoodsService.class);
			ServletContext application = context.getBean(ServletContext.class);
			System.out.println(2);
			init(application);
		}
	}
	
	/**
	 * 	初始化application，这个定时器在关闭服务器的时候没有关
	 * 
	 * */
	private void init(ServletContext application) {
		// 首次加载先运行
		task(application);
		
		// 启动定时器
        long daySpan = 24 * 60 * 60 * 1000; // 一天的毫秒数
        // 规定的每天时间00:00:00运行
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        try {
        	// 首次运行时间
			Date firstTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
			// 如果今天的已经过了，首次运行时间就改为明天
            if (System.currentTimeMillis() > firstTime.getTime()){
            	firstTime = new Date(firstTime.getTime() + daySpan);
            }
            Timer timer = new Timer();
    		TimerTask task = new TimerTask() {
    			@Override
    			public void run() {
    				// 定时器执行：更新application里的数据
    				task(application);
    			}
    		};
    		timer.schedule(task, firstTime, daySpan);
    		log.info("定时器启动成功！");
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 	定时器执行的任务
	 * 
	 */
	private void task(ServletContext application) {
		System.out.println(1);
		activeUserTask(application);
		indexContentTask(application);
	}
	
	/**
	 * 	添加活跃用户
	 * 	TODO Redis优化
	 * 
	 * */
	private void activeUserTask(ServletContext application) {
		if(application == null || wantService == null) {
			log.error("application或wantService为null");
			return;
		}
		List<Want> wantList = wantService.findWantAll(null);
		List<ActiveUser> activeUserAll = new ArrayList<>(); // 所有的活跃用户
		List<ActiveUser> activeUserList = new ArrayList<>(5); // 活跃用户前5名
		// 查找活跃用户中有没有这个用户
		for (Want want : wantList) {
			boolean flag = false;
			for (ActiveUser _activeUser : activeUserAll) {
				if (_activeUser.getUid().equals(want.getUser().getUid())) {
					// 若有则count+1
					Integer count = _activeUser.getCount();
					_activeUser.setCount(++count);
					flag = true;
					break;
				}
			}
			if (!flag) {
				// 若没有则新创建一个
				ActiveUser activeUser = new ActiveUser();
				activeUser.setCount(1);
				activeUser.setImgPath(want.getUser().getImgPath());
				activeUser.setNickname(want.getUser().getNickname());
				activeUser.setUid(want.getUser().getUid());
				activeUserAll.add(activeUser);
			}
		}
		// 取前5名
		int i = 0;
		while (i < 5 && i < activeUserAll.size()) {
			for (int j = i + 1; j < activeUserAll.size(); j++) {
				if (activeUserAll.get(i).getCount() < activeUserAll.get(j).getCount()) {
					ActiveUser temp = activeUserAll.get(i);
					activeUserAll.set(i, activeUserAll.get(j));
					activeUserAll.set(j, temp);
				}

			}
			activeUserList.add(activeUserAll.get(i));
			i++;
		}
		application.setAttribute(Info.ACTICE_USER_APPLICATION, activeUserList);
	}
	
	/**
	 * 	获取首页内容
	 * 
	 * */
	private void indexContentTask(ServletContext application) {
		if(application == null || goodsService == null) {
			System.out.println("application或goodsService为null");
			return;
		}
		List<IndexGoods> indexGoodsList = new LinkedList<>();
		String condition = "goods.isSelected desc,goods.view desc,goods.time desc";
		// 手机
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("手机", condition, 1, 5, null, null), "手机");
		// 电脑
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("电脑", condition, 1, 5, null, null), "电脑");
		// 音响
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("音响", condition, 1, 5, null, null), "音响");
		// 键盘
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("键盘", condition, 1, 5, null, null), "键盘");
		// 运动
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("运动", condition, 1, 5, null, null), "运动系列");
		// 衣物
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("衣物鞋帽", condition, 1, 5, null, null), "衣物");
		// 二手书
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("书", condition, 1, 5, null, null), "二手书");
		// 车子
		addIndexGoodsList(indexGoodsList, goodsService.searchGoodsAll("车", condition, 1, 5, null, null), "车子");
		application.setAttribute(Info.INDEX_CONTENT_APPLICATION, indexGoodsList);
	}
	
	/**
	 * 	若发布商品2周内还未卖出，若商品标签存在最新上架，则把最新上架换为快来点我吧
	 * 
	 * */
	private void cancelNewLabelTask(ServletContext application) {
		
	}
	
	/**
	 * 	添加首页内容list集合
	 * 
	 * */
	private void addIndexGoodsList(List<IndexGoods> indexGoodsList, PageBean<Goods> pageBean, String type) {
		if(pageBean != null) {
			for(Goods goods : pageBean.getBeanList()) {
				IndexGoods indexGoods = new IndexGoods();
				indexGoods.setDetails(goods.getDetails());
				indexGoods.setImgPath(goods.getImgPath().split(";")[0]);
				indexGoods.setPrice(goods.getRealPrice());
				indexGoods.setType(type);
				indexGoods.setUrl("/qb/page/user/search/desc.html?" + goods.getGid());
				indexGoodsList.add(indexGoods);
			}
		}
	}
}
